package com.tuhu.server.db.op;

import com.tuhu.server.db.DBConn;
import com.tuhu.server.db.DBHelper;
import com.tuhu.server.util.IOUtil;
import com.tuhu.server.util.TimeUtil;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class HeartBeatDB {

    public static int heartConn() {
        String time = TimeUtil.convert(System.currentTimeMillis(), TimeUtil.TIME_FORMAT_YYYY_MM_DD_HH_MM_SS);
        String sql = String.format("INSERT INTO heartbeat (conn_time) VALUES ('%s')", time);


        PreparedStatement pstmt = null;
        ResultSet rs = null;
        int id = -1;
        try {
            pstmt = DBConn.getInst().getCoon().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            pstmt.executeUpdate();
            rs = pstmt.getGeneratedKeys();
            if (rs.next()) {
                id = rs.getInt(1);
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        } finally {
            // 关闭资源
            IOUtil.close(rs);
            IOUtil.close(pstmt);
        }

        System.out.println("--------心跳连接: count=" + id + " , time=" + time);

        if (id % 90 == 0) {
            String sqlDel = String.format("DELETE FROM heartbeat");
            DBHelper.executeUpdate(sqlDel);
        }

        //每20分钟清理一次内存垃圾
        if (id % 60 == 0) {
            System.gc();
            System.out.println("--------主动GC垃圾回收: id=" + id + " , time=" + time);
        }

        return id;
    }

}
